<?php
class IndexAction extends TopAction {
	public function index() {
		//var_dump( $_SESSION );
		//print_r($_SESSION);
		//$this->getseller ();
		$this->display ();
	}
	public function t() {
		 
		$f = D('Trade')->filterTrade( '9224196264862117' , '');
		var_dump( $f );
		echo D()->_sql();
		exit;
		$skus = D('Productsetting')->getInventoryList('prosku,proinventory');
		echo D()->_sql();
		print_r( $skus );
		
		exit;
		D('Trade')->startTrans();
		
		//print_r($p);
		$d['paycode'] = '20130721004230392785';
		var_dump( $x );
		echo '<hr>';
		D('Payment')->where(' id = 65 ') ->save( $d ) ;
		D('Trade')->rollback();
		//var_dump( $p );
		var_dump( D('Trade') );
		exit;
		$ptid = $_GET['id'];
		$tplid = $_GET['id'];
		$comid = D('Posttemplate')->where("ID={$tplid}")->getField('comid');
		print_r( $comid );
		echo D()->_sql();
		exit;
		
		$post = array();
		$post['base'] = M('posttemplate')->where( " id = '{$ptid}' ")->find();
		$post['district'] = M('posttemplatedistrict')->where(" tplid = {$post['base']['id']} AND dname='北京市' ")->find();
		print_r($post); 
		
		$rrr = D("Trade")->getProductBySku( 'test_789_38' );
		print_r ( $rrr );
		
		
		$ttt = D('Postsetting')->getTemplates(1);
		print_r( $ttt ); 
	}
	
	/**
	 * 订单列表
	 * 目前直接读取API
	 * 查询3个月内已付款的订单
	 * @todo 当查询API请求太多考虑用缓存 比如3分钟内只能请求一次 或手动执行更新订单 否则是缓存
	 * 
	 */
	public function tradelist() {
		$page = $_p = intval ( $_GET ['p'] ) ? intval ( $_GET ['p'] ) : 1;
		
		//$cache_key = "orders_{$page}";
		$cache_key = "trade_{$_SESSION['seller_nick']}_{$page}";
		//$orders = S ( $cache_key );
		//$companys  = D("Postsetting")->viewCompanys( 1 );
		$templates = D('Postsetting')->getTemplates( 1 );
		foreach ( $templates as $template) {
			$tploptions .= "<option value='{$template['id']}'>{$template['tplname']}</option>";
		}
		$ps = D ( 'Postsetting' );
		$districts = $ps->getDistrict ();
		$out = '';
		foreach ( $districts as $dist ) {
			$selected = ( $cityid == $dist['id'] ) ? ' selected="selected"' : '';
			$district .= '<option value="'. U('Index/tradelist?did='.$dist ['id'] ) .'" '.$selected.'>' . $dist ['name'] . '</option>';
		}
		$did = intval( $_GET['did'] );
		
		
		if (empty ( $orders )) {
			//echo '::::::GET API::::::';
			$params = array (
					'method' => 'taobao.trades.sold.get',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
					
					'fields' => 'seller_nick,buyer_nick,num,tid,buyer_message,payment,buyer_memo,seller_memo,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders,orders.pic_path,orders.sku_properties_name,orders.outer_sku_id,pic_path,seller_flag,status,created,post_fee,shipping_type',
					'status' => 'WAIT_SELLER_SEND_GOODS',
					'page_no' => $page,
					'page_size' => 100
			);
			
			$tc = new TopClient ();
			
			$orders = $tc->getResult ( $params );
			foreach( $orders['trades_sold_get_response']['trades']['trade'] as $k=>$tmporder ) {
				$session_trade[ number_format( $tmporder['tid'] , 0, '', '' ) ] = $tmporder ;
			}
			unset($tmporder);
			$orders = $this->filterTrades( $orders ) ;
			if( $did ) {
				$disname = $ps->getDiscrictName( $did );
			 	if( $disname ) {
					foreach( $orders['trades_sold_get_response']['trades']['trade'] as $k=>$tmporder ) {
						if( $tmporder['receiver_state'] != $disname ) {
							unset( $orders['trades_sold_get_response']['trades']['trade'][$k] );
						}
					}
					
				}
			}
			
			//$_SESSION['trade'] = $session_trade;
			//F ( $cache_key, $session_trade );
			//unset( $session_trade );
			//获取订单详情*********************************************
			foreach( $orders['trades_sold_get_response']['trades']['trade'] as $k=>$tmporder ) {
				//$tids .= $tmporder['tid'].';';
				$fullinfo = array();
				for( $i=0;$i<3;$i++) {
					$params = array (
							'method' => 'taobao.trade.fullinfo.get',
							'session' => $this->_top_session,
							'timestamp' => date ( 'Y-m-d H:i:s' ),
							'format' => TAO_RETURN_FORMAT,
							'app_key' => TAO_APPKEY,
							'v' => '2.0',
							'sign_method' => 'md5',
								
							'fields' => 'buyer_message,seller_memo',
							'tid' => $tmporder['tid']
					);
					$fullinfo = $tc->getResult( $params );
					Log::write( 'fullinfo.get::::'. str_replace( PHP_EOL, ' ',  var_export( $fullinfo, true) ).'_i:'.$i.'_tid:'.$tmporder['tid'].'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.fullinfo.log' );
					if(! empty( $fullinfo ) ) break;
				}
					
				$orders['trades_sold_get_response']['trades']['trade'][$k]['buyer_message'] = 	$fullinfo['trade_fullinfo_get_response']['trade']['buyer_message'];
				$orders['trades_sold_get_response']['trades']['trade'][$k]['seller_memo'] = 	$fullinfo['trade_fullinfo_get_response']['trade']['seller_memo'];
			}
			//获取订单详情end*********************************************
			
			
			//S ( $cache_key, $orders, 180 );
		    
			foreach( $orders['trades_sold_get_response']['trades']['trade'] as $trade ) {
				$tradeTmp[  number_format( $trade['tid'], 0, '', '' ) ] = $trade['receiver_name'] .','. $trade['receiver_mobile'] . ','. $trade['receiver_phone'] .',' . $trade['receiver_state'] .', '. $trade['receiver_city']. ' '. $trade['receiver_district'] .','. $trade['receiver_address'] .','. $trade['receiver_zip'];
				$tradeTmp2[  number_format( $trade['tid'], 0, '', '' ) ] = $trade;
			}
			
// 			print_r( $tradeTmp );
			$trade_count = array_count_values( $tradeTmp );
// 			print_r( $trade_count );
			foreach ( $trade_count as $tkey => $tcount ) {
				if( $tcount === 1 ) continue;
				$trade_mergeTmp[] = $tkey;
			}

			if( $trade_mergeTmp ) { 
				foreach ( $trade_mergeTmp as $tmt ){
					$trade_merge[] = array_keys( $tradeTmp , $tmt  );
				}
			}
			//$tradeTmp
			//$tm  tid1  tid2
			//print_r( $trade_merge );
			$trade_mergeR = array( );
			foreach( $trade_merge as $k=>$tm ){
				$tidf = number_format( $tm[0] , 0, '', '' ) ;
				$tmids = '';
				$tmPayment = 0;
				$tmNum = 0;
				$trade_mergeR[ $tidf ] = $tradeTmp2[ $tidf ];
				$tmOrder = array( );
				$tmSeller_memo = $tmBuyer_message = '';
				$tmPost_fee = $tmShiping_type = '';
				foreach( $tm as $kk=>$t){					
					$tmOrder = array_merge( $tmOrder , $tradeTmp2[$t]['orders']['order'] );
					$tmids 	.= $t .',';
					$tmPayment 	+= $tradeTmp2[$t]['payment'];
					$tmSeller_memo .= $tradeTmp2[$t]['seller_memo'] ? 		$tradeTmp2[$t]['seller_memo'].';' : '' ;
					$tmBuyer_message .= $tradeTmp2[$t]['buyer_message'] ? 	$tradeTmp2[$t]['buyer_message'].';' : '' ;
					$tmPost_fee .= $tradeTmp2[$t]['post_fee'] ? 			$tradeTmp2[$t]['post_fee'].';<br>' : '' ;
					$tmShiping_type .= $tradeTmp2[$t]['shipping_type'] ? 	shipping_type ( $tradeTmp2[$t]['shipping_type'] ).';<br>' : '' ;
				}
				$trade_mergeR[ $tidf ]['payment'] 	= $tmPayment;
				$trade_mergeR[ $tidf ]['orders']['order'] = $tmOrder;
				$trade_mergeR[ $tidf ]['seller_memo'] 	= $tmSeller_memo;
				$trade_mergeR[ $tidf ]['buyer_message'] 	= $tmBuyer_message;
				$trade_mergeR[ $tidf ]['post_fee'] 	= $tmPost_fee;
				$trade_mergeR[ $tidf ]['shipping_type'] 	= $tmShiping_type;
				
				$trade_mergeR[ $tidf ]['systids'] = trim($tmids , ',' );
				$trade_mergeR[ $tidf ]['systids'] = trim($tmids , ',' );
			}
			//print_r ( $trade_mergeTmp );
			$tosaveTrade = array_merge( $session_trade , $trade_mergeR  );
			F ( $cache_key, $tosaveTrade );
			//var_dump( $session_trade , $trade_mergeR, $tosaveTrade );
			//$_SESSION['trade_merge'] = $trade_mergeR;
			//print_r( $_SESSION['trade_merge'] );
			unset( $trade_merge );
			unset( $tradeTmp );
			unset( $tradeTmp2 );
			unset( $tradeTmp2 );
		}
		if( $trade_mergeR ) {
			//把在合并订单的ID过滤掉
			$orders = $this->filterMergeTrade( $orders, $trade_mergeR );
		}
		
		//退款的
		
		$params = array (
				'method' => 'taobao.refunds.receive.get',
				'session' => $this->_top_session,
				'timestamp' => date ( 'Y-m-d H:i:s' ),
				'format' => TAO_RETURN_FORMAT,
				'app_key' => TAO_APPKEY,
				'v' => '2.0',
				'sign_method' => 'md5',
					
				'fields' => 'tid',
				'page_size' => 100,
		);
			
		for( $i=0;$i<3;$i++) { 
			$refounds = $tc->getResult ( $params );
			if(! empty( $refounds ) ) break;
		}
		if( $refounds ['refunds_receive_get_response'] ['total_results'] > 0  ) {
			foreach( $refounds ['refunds_receive_get_response'] ['refunds'] ['refund']  as $refund ) {
				$refundTrade[ $refund['tid'] ] = $refund ;
			}
		}
		
		//{"refunds_receive_get_response":{"total_results":0}}
		
		$count = $orders['trades_sold_get_response']['total_results'];
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, 100 );
		$page = $p->show ();
		
		
		$this->assign( 'tploptions', $tploptions );
		$this->assign( 'district', $district );
		
		$this->assign('p', $_p);
		$this->assign ( "page", $page );
		$this->assign( 'tploptions', $tploptions );
		$this->assign ( 'orders', $orders );
		$this->assign( 'trade_mergeR' , $trade_mergeR );	//合并的订单
		//$this->assign( 'tradeTmp' , $tradeTmp );
		
		$this->assign('did', $did );
		
		$this->assign( 'refund' , $refundTrade ) ;
		$this->display ();
		
		 
	}
	
	
	function price ( ) {
		$tid = $_POST['tid'];	
		$page = intval( $_POST['p'] ) ? intval( $_POST['p'] )  : 1 ;
		$cache_key = "trade_{$_SESSION['seller_nick']}_{$page}";
		//echo $cache_key;
		$trades = F( $cache_key);
		$trade =  $trades[ $tid ];
		if (empty( $trade)) $this->error( '订单获取错误' );
// 		$trade = D('Trade')->getTradePrice( unserialize( $_POST['trade'] ), $_POST['tplid'] );
		$trade = D('Trade')->getTradePrice( $trade , $_POST['tplid'] );
		if( $trade ){
			$this->ajaxReturn($trade , '',1);
		}else{
			Log::write( 'price.get::::post:'. str_replace( PHP_EOL, ' ',  var_export(  $_POST['trade'] , true) ).'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.price.log' );
			$this->error( 'sku_id不存在' );	
		}
		
	}
	
	/**
	 * 快递信息
	 */
	public function logisticscompany() {
		$Cache = Cache::getInstance ();
		$Cache->setOptions ( 'expire', '3600' );
		$Cache->setOptions ( 'prefix', 'logisticscompany' );
		$cache_key = 'logisticscompany';
		$logisticscompany = $Cache->get ( $cache_key );
		
		if (! $logisticscompany) {
			$params = array (
					'method' => 'taobao.logistics.companies.get',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
					
					'fields' => 'id,code,name,reg_mail_no' 
			);
			
			$tc = new TopClient ();
			
			$logisticscompany = $tc->getResult ( $params );
			
			$Cache->set ( $cache_key, $logisticscompany );
		}
		print_r( $logisticscompany ['logistics_companies_get_response'] ['logistics_companies'] ['logistics_company']  );
// 		foreach ( $logisticscompany ['logistics_companies_get_response'] ['logistics_companies'] ['logistics_company'] as $company ) {
// 			$item = array (
// 					'code' => $company ['code'],
// 					'id' => $company ['id'],
// 					'name' => $company ['name'],
// 					'reg_mail_no' => $company ['reg_mail_no'] 
// 			);
// 			M ( 'company' )->add ( $item );
// 			echo M ()->_sql ();
// 		}
	}
	public function mm() {
		$provinces = M ( 'district' )->where ( 'level=1' )->select ();
		echo M ()->getLastSql ();
		var_dump ( $provinces );
	}
	/**
	 * 保存API获取的订单信息
	 */
	public function tradesave() {
		$page = intval( $_POST['p'] ) ? intval( $_POST['p'] )  : 1 ;
		
		$tid = $_POST['tid'];
		$cache_key = "trade_{$_SESSION['seller_nick']}_{$page}"; 
		//echo $cache_key;
		$trades = F( $cache_key);
		$trade =  $trades[ $tid ];
		//print_r( $trade);
		//exit;
		//$trade = $_POST['trade'];
		//$trade = unserialize( $trade );
		
		$tplid = intval( $_POST['tplid'] );
		if(empty( $tplid) ) $this->error( '快递ID为空');
		if( empty( $trade) ) $this->error( '订单获取错误' );
		//print_r( $price );
		//检查订单是否已入库
		$tidinfo = D('Trade')->filterTrade( $tid, $trade['tids'] );
		if( ! empty( $tidinfo ) )  {
			Log::write( 'tradesave:filterTrade::::'. str_replace( PHP_EOL, ' ',  $tidinfo ).'_i:'.D('Trade')->_sql().'_tid:'.$trade['tid'].'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.tradesave.log' );
			$this->error ( $tidinfo['tid'].'订单已入库'.D()->_sql() );
		}
		
		
		foreach ( $trade ['orders']['order'] as $k=>$order ) {
			$productsku[ $k ] = D('Trade')->getProductBySku( $order['outer_sku_id'] );
			if( $productsku[ $k ] ['proinventory'] < $order['num'] ) {
				$error.= $order['outer_sku_id'] .'库存不足:'.$productsku[ $k ] ['proinventory'];
			}
		}
		
		//计算价格  快递费用
		$comid = D('Posttemplate')->where("ID={$tplid}")->getField('comid');
		$price = D('Trade')->getTradePrice( $trade, $tplid );
		
		
		$trade['syscprice'] = $price['cprice'];
		$trade['sysvprice'] = $price['vprice'];
		$trade['syspostprice'] = $price['post'];
		$trade['syscost'] = $price['cost'];
		$trade['sysprofit'] =  $trade['payment'] - $price['post'];		//订单金额-cost
		$trade['sysstatus'] = 1;
		$trade['systplid'] = $tplid;
		$trade['syscomid'] = $comid;
		$trade['sysaddtime'] = date('Y-m-d H:i:s');
		$trade['systids'] = $trade['systids'];
		//
		$sellerpaybaylance= D('Trade')->getSellerPaybalance( $_SESSION['seller_nick'] );//卖家的系统金额
		 
		//检查库存和 卖家余额
		//余额和POST价做比较
		if( $sellerpaybaylance < $price['cost'] ){
			$this->error('卖家系统余额不足,余额:'.$sellerpaybaylance );
		} 
		if(  $error ) {
			$this->error( $error );
		}
		
		//extract( $trade);
// ;		print_r( $trade );
		
		
			D('Trade')->startTrans ();
			$pay = D('Payment')->paymentUpdate( 2 , $_SESSION['seller_nick'], $price['cost'] , $tid, false );
			
			if(1 == $pay['status']) {
				
				foreach ( $trade ['orders']['order'] as $order ) {
					$tup = D('Trade')->updateProinventory ( $order['outer_sku_id'], $order['num'], $_SESSION['seller_nick'], '-', '提交订单', false  );
					if( false == $tup ) {
						D('Trade')->rollback();
						$this->error ( '库存更新失败' );
					}
				}
				
				$trade['orders'] = serialize( $trade['orders'] );
				
				$vo = M('Trade')->add( $trade );
				//echo D()->_sql();	 
				if( $vo ) {
					$log['tid'] =  $trade['tid'];
					$log['loguser'] = $trade['seller_nick'];
					$log['logtext'] = '商家提交订单';
					$log['logtime'] = date('Y-m-d H:i:s');
					$log['role'] = 'seller';
					D('Tradelog')->add( $log );
					
					//更新库存
					D('Trade')->commit();
					$this->ajaxReturn ( $vo, '订单提交成功！', 1 );
				}else {
					D('Trade')->rollback();
					$this->error ( D('Trade')->getError (  ) );
				}
					
			} else { 
				D('Trade')->rollback();
				$this->error( $pay['info']. var_export( $pay , 1) );
			}
		
	}
	
	
	/**
	 * 批量提交
	 */
	public function tradesaveall() {
		$tidall = $_POST['tid'];
		$tplid 	= $_POST['tplid'];
		if( empty( $tidall ) ) $this->error( '未提交订单' );
		if( empty( $tplid ) ) $this->error( '未选择快递模板' );
		//var_dump( $_SESSION['trade'] );
		foreach ( $tidall as $tid ) {
			
			$trade = $_SESSION['trade'][ $tid ];
			
			//检查订单是否已入库
			$tidinfo = D('Trade')->filterTrade( $tid );
 		
			if( ! empty( $tidinfo ) )  {
				Log::write( 'tradesave:filterTrade::::'. str_replace( PHP_EOL, ' ',  var_export( $tidinfo, true ) ).'_i:'.$i.',sql:'. D('Trade')->_sql().'_tid:'. $tid .'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.tradesaveall.log' );
				$error .=  ( $trade['tid'].'订单已入库' ).',';
				continue;
				
				
			}
			//echo D()->_sql();
			//continue;
		
			foreach ( $trade ['orders']['order'] as $k=>$order ) {
				$productsku[ $k ] = D('Trade')->getProductBySku( $order['outer_sku_id'] );
				if( $productsku[ $k ] ['proinventory'] < $order['num'] ) {
					$error.= $tid.'未能提交:::'.$order['outer_sku_id'] .'库存不足:'.$productsku[ $k ] ['proinventory'].',';
					continue 2 ;
				}
				//continue;
			}
			
			//计算价格  快递费用
			$comid = D('Posttemplate')->where("ID={$tplid}")->getField('comid');
			$price = D('Trade')->getTradePrice( $trade, $tplid );
		
		
			$trade['syscprice'] = $price['cprice'];
			$trade['sysvprice'] = $price['vprice'];
			$trade['syspostprice'] = $price['post'];
			$trade['syscost'] = $price['cost'];
			$trade['sysprofit'] =  $trade['payment'] - $price['post'];		//订单金额-cost
			$trade['sysstatus'] = 1;
			$trade['systplid'] = $tplid;
			$trade['syscomid'] = $comid;
			$trade['sysaddtime'] = date('Y-m-d H:i:s');
			//$trade['systids'] = $trade['tids'];
			//
			$sellerpaybaylance= D('Trade')->getSellerPaybalance( $_SESSION['seller_nick'] );//卖家的系统金额
				
			//检查库存和 卖家余额
			//余额和POST价做比较
			if( $sellerpaybaylance < $price['cost'] ){
				$this->error('卖家系统余额不足,余额:'.$sellerpaybaylance );
			}
			if(  $error ) {
				continue;
				
			}
		
			D('Trade')->startTrans ();
			$pay = D('Payment')->paymentUpdate( 2 , $_SESSION['seller_nick'], $price['cost'] , $tid, false );
				
			if(1 == $pay['status']) {
		
				foreach ( $trade ['orders']['order'] as $order ) {
					$tup = D('Trade')->updateProinventory ( $order['outer_sku_id'], $order['num'], $_SESSION['seller_nick'], '-', '提交订单', false  );
					if( false == $tup ) {
						D('Trade')->rollback();
						$this->error ( '库存更新失败' );
					}
				}
		
				$trade['orders'] = serialize( $trade['orders'] );
		
				$vo = M('Trade')->add( $trade );
				//echo D()->_sql();
				if( $vo ) {
					$log['tid'] =  $tid;
					$log['loguser'] = $trade['seller_nick'];
					$log['logtext'] = '商家提交订单';
					$log['logtime'] = date('Y-m-d H:i:s');
					$log['role'] = 'seller';
					D('Tradelog')->add( $log );
						
					//更新库存
					D('Trade')->commit();
					$success .= $tid .'提交成功,';
					$data 	.= $tid.',';
					//$this->ajaxReturn ( $vo, '订单提交成功！', 1 );
				}else {
					D('Trade')->rollback();
					$error .= $tid.'提交失败：'.D('Trade')->getError (  ).'数据更新错误,';
					//$this->error ( D('Trade')->getError (  ) );
				}
					
			} else {
				D('Trade')->rollback();
				$error .= $tid.'提交失败：'. $pay['info'].',';
				//$this->error( $pay['info']. var_export( $pay , 1) );
			}
		
		}
		if( $data ){
			$data = trim($data, ',');
		}
		
		$this->ajaxReturn( $data, $error , 1 );
	}
	
	
	/**
	 * 待发货订单 
	 * sysstatus = 1 
	 */
	function tradelist2 () {
		$seller_nick = $_SESSION['seller_nick'];
		$count = D ( 'Trade' )->where("sysstatus = 1 AND seller_nick='$seller_nick'")->count ();
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, $this->pagesize );
		$tradelist = D ( 'Trade' )->where("sysstatus = 1 AND seller_nick='$seller_nick'")->limit ( $p->firstRow . ',' . $p->listRows )->order ( "sysaddtime DESC" )->select ();
		
		$page = $p->show ();
		$this->assign ( "page", $page );
		$this->assign( 'tradelist', $tradelist );
		$this->display();	
	}
	/**
	 * 已发货订单
	 */
	function tradelist3 () {
		$seller_nick = $_SESSION['seller_nick'];
		$count = D ( 'Trade' )->where("sysstatus = 2 AND seller_nick='$seller_nick'")->count ();
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, $this->pagesize );
		$tradelist = D ( 'Trade' )->where("sysstatus = 2 AND seller_nick='$seller_nick'")->limit ( $p->firstRow . ',' . $p->listRows )->order ( "sysaddtime DESC" )->select ();
	
		
		$templates = D('Postsetting')->getTemplates( 1 );
		foreach ( $templates as $template) {
			$tploptions .= "<option value='{$template['id']}'>{$template['tplname']}</option>";
		}
		
		
		$this->assign ( 'tradelist', $tradelist );
		$this->assign("status", TradeAction::TRADE_STATUS_SHIPPED);
		
		$this->assign( 'tploptions', $tploptions );
		
		$page = $p->show ();
		$this->assign ( "page", $page );
		$this->assign( 'tradelist', $tradelist );
		$this->display();
	}
	/**
	 * 待处理页面
	 * 把已发货订单里面红色五角星的筛选出来就可以了
	 */
	function tradelist4 () {
		$seller_nick = $_SESSION['seller_nick'];
		$count = D ( 'Trade' )->where("sysstatus = 2 AND systodo=1 AND seller_nick='$seller_nick'")->count ();
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, $this->pagesize );
		$tradelist = D ( 'Trade' )->where("sysstatus = 2 AND systodo=1 AND seller_nick='$seller_nick'")->limit ( $p->firstRow . ',' . $p->listRows )->order ( "sysaddtime DESC" )->select ();
		
		$page = $p->show ();
		$this->assign ( "page", $page );
		$this->assign( 'tradelist', $tradelist );
		$this->display();
	}

	function payment() {
		$nick = $_SESSION['seller_nick'];
		$seller = D('Seller')->where("nick='{$nick}'")->find();
		$paybalance = $seller['paybalance'];
		
		$count = D('Payment')->where("nick='{$nick}'")->count();
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, $this->pagesize );
		
		$paylog = D('Payment')->where("nick='{$nick}'")->limit ( $p->firstRow . ',' . $p->listRows )->order("ID DESC")->select();
		$page = $p->show ();
		$this->assign ( "page", $page );
		$this->assign('paybalance', $paybalance );
		$this->assign('paylog', $paylog );
		$this->display();
	}
	
	/**
	 * 同步库存
	 */
	function inventory () {
		//系统库存
		$proinventory = D('Productsetting')->getInventoryList('prosku,proinventory');
		foreach( $proinventory as $pro) {
			$sysprosku[ $pro[prosku] ] = $pro[proinventory];
		}
		//print_r( $sysprosku );
		
		
		$page = 1;
		//获取在售商品
		$params = array (
				'method' => 'taobao.items.onsale.get',
				'session' => $this->_top_session,
				'timestamp' => date ( 'Y-m-d H:i:s' ),
				'format' => TAO_RETURN_FORMAT,
				'app_key' => TAO_APPKEY,
				'v' => '2.0',
				'sign_method' => 'md5',
	
				'fields' => 'num_iid',
	
				'page_no' => $page,
				'page_size' => 200
		);
			
		$tc = new TopClient ();
			
		$onsales = $tc->getResult ( $params );
		//print_r( $onsales );
		//SKUS 每页做多获取40个
		$pages = ceil ( count( $onsales['items_onsale_get_response']['items']['item'] ) / 40 );
	
		$page = 0;
		foreach ( $onsales['items_onsale_get_response']['items']['item'] as $k=>$item ) {
				
			//获取SKU
			if($k>0 &&  0 == $k % 40 ) {
				$page++;
			}
			$num_iids[$page] .= $item['num_iid'] . ',';

		}

		$skus = array( );
		for( $i=0; $i< $pages; $i++) {
			//echo '====GET SKUS:'.$i .'====';
			$params = array (
					'method' => 'taobao.item.skus.get',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
						
					'fields' => 'outer_id,num_iid,sku_id',
						
					'num_iids' => $num_iids[$i],
						
			);
				
				
			$skus[$i] = $tc->getResult ( $params );
		}
		//print_r( $skus );
		foreach( $skus as $item ) {
			foreach($item[item_skus_get_response][skus][sku] as $sku ){
				//print_r( $sku );
				$num_iidstr = strval($sku[num_iid]);
				$sku_idstr  = strval( $sku[sku_id] );
				$prosku[ $num_iidstr ][ $sku[outer_id] ] = $sku[num_iid];	//NUM_IID下对应的所有SKU
				$skuid[ $sku_idstr ][ $num_iidstr ]	= $sku[outer_id] ;
			}
			
		}
		//echo "prosku :";
 		//print_r( $prosku );
		$sku_intersect = array( );
		foreach( $prosku as $num_iid_key => $num_iidtmp ) {
			//echo 'num_iidtmp';
			//print_r( $num_iidtmp );
			$sku_intersect = array_intersect_key($sysprosku, $num_iidtmp );
			//print_r( $sku_intersect );
			if( empty( $sku_intersect ) ) {
				$error[ ] = $num_iid_key.'SKU没有匹配项:'. implode( ',', $num_iidtmp );
			}else {
				foreach ( $sku_intersect as $sku => $inventory ){
					$quantities[ strval( $num_iidtmp[$sku]) ] .= $sku.':'.$inventory.';' ;
				}
			
			}
		}
		//echo 'quantities:';
		//print_r( $quantities );
		//更新库存
		foreach ( $quantities as $num_iid => $outerid_quantities ){
			$params = array (
					'method' => 'taobao.skus.quantity.update',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
	
						
					'num_iid'	=> $num_iid,
					'outerid_quantities' => $outerid_quantities,
	
			);
			$ret[ ] = $tc->getResult ( $params );
		}
		//print_r( $ret );
		//var_dump( $error );
		//echo "skuid::::";
		//print_r( $skuid );
		
		if( $ret ) {
			$retstr = '更新完成:<br>';
			if( $error ) {
				$retstr .= '以下商品SKU不匹配';
				foreach ( $error as $err  ) {
					
					$retstr .= $err.'<br>';
				}
			}
			$retstr .= '以下商品已更新<br>';
			foreach( $ret as $report ) {
				if( $report [skus_quantity_update_response][item] ) {
					foreach ( $report [skus_quantity_update_response][item][skus][sku] as $itemsku ) {
						$itemsku_id = strval($itemsku[sku_id]) ;
						$retstr .= $itemsku[modified].'---' . key( $skuid[ $itemsku_id ] ) .'------'.$skuid[ $itemsku_id ][ key( $skuid[ $itemsku_id ] ) ]. '----'. $itemsku[quantity]."<br>";
	
					}
				}
	
			}
			$this->ajaxReturn('',$retstr,1);
			
		}
	
	
	}

	function tradetodo () {
		$tid = $_POST[tid];
		$systodo = D('Trade')->where("tid='{$tid}'")->field('systodo')->find();
	    
		$data[systodo] = $systodo['systodo'] == 1 ? 0 : 1 ;
		$vo = D('Trade')->where("tid='{$tid}'")->save( $data ) ;
		if ($vo) {
			$this->ajaxReturn ( $data[systodo], '成功', 1 );
		} else {
			$this->error ( D('Trade')->getError () );
		}
	}
	
	function tradefeedback () {
		$tid =  $_GET['tid'] ;
		if( $tid ) {
			$trade = D('Trade')->where("tid={$tid}")->find();
			$tradefeedback = D('Tradefeedback')->where("tid={$tid}")->select();
	
			$this->assign( 'tid', $tid );
			$this->assign( 'trade', $trade );
			$this->assign( 'tradefeedback', $tradefeedback );
			$this->display();
		}
	}
	
	function tradefeedbacksave () {
		$vo = D('Tradefeedback')->create($_POST);
		
		if( $vo ) {
			$seller_nick = $_SESSION['seller_nick'] ;
			$role = $_SESSION['role'];
		    $vo['seller_nick'] = $seller_nick;
		    $vo['role'] = $role;
		    $vo['addtime'] = date('Y-m-d H:i:s');
			D('Tradefeedback')->add( $vo );
			
			$tid = $vo['tid'];
			//$data['sysstatus'] = self::TRADE_STATUS_PENDING;
			D('Trade')->where("tid={$tid}")->save($data);
			
			
			$log['tid'] =  $tid;
			$log['loguser'] = $_SESSION['seller_nick'];
			$log['logtext'] = '待处理';
			$log['logtime'] = date('Y-m-d H:i:s');
			$log['role'] = $role;
			D('Tradelog')->add( $log );
			
			
			$this->ajaxReturn($vo, '处理成功' , 1);
			
		}else{
			$this->error( D('Tradefeedback')->getError() );
		}
		
	}
	
	function tradefeedbackcancel () {
		$tid = $_POST['tid'];
		$data['systodo'] = 0; 
		$vo = D('Trade')->where("tid={$tid}")->save($data);
		if( $vo ) {
				
			$log['tid'] =  $tid;
			$log['loguser'] = $_SESSION['seller_nick'];
			$log['logtext'] = '取消待处理';
			$log['logtime'] = date('Y-m-d H:i:s');
			$log['role'] = 'seller';
			D('Tradelog')->add( $log );
				
			$this->ajaxReturn( $vo, '已取消处理', 1);
		}else {
			$this->error( 'ERROR'.D('Trade')->getError() );
		}
	
	}
	
	function tradesearch( ) {
		$map[field] = $_POST['field'] ? htmlspecialchars( $_POST['field'] ) : htmlspecialchars( $_GET['field'] );
		$map[k] = $_POST['k'] ?htmlspecialchars( $_POST['k'] ) : htmlspecialchars( $_GET['k'] );
		$map[tplid] = $_POST[tplid] ? intval( $_POST[tplid] ) : intval( $_GET[tplid] );
		if( $map[field]  == 'tplid' && $map[tplid] ) {
			$wherestr = " AND systplid='{$map[tplid]}' ";
		}else {
			$wherestr = $map[k] ? " AND {$map[field]} = '{$map[k]}' " : "" ;
		}
		$status = $_POST[status] ? intval( $_POST[status] ) : intval( $_GET[status] );
		$count = D ( 'Trade' )->where ( "sysstatus = {$status} AND seller_nick='{$_SESSION['seller_nick']}' {$wherestr} ")->count ();
		import ( "ORG.Util.Page" ); // 导入分页类
		$p = new Page ( $count, $this->pagesize );
		$tradelist = D ( 'Trade' )->where ( "sysstatus = {$status} AND seller_nick='{$_SESSION['seller_nick']}' {$wherestr} ")->limit ( $p->firstRow . ',' . $p->listRows )->order ( "sysaddtime DESC" )->select ();
		
		//echo D()->_sql();
	
		$templates = D('Postsetting')->getTemplates( 1 );
		foreach ( $templates as $template) {
		$tploptions .= "<option value='{$template['id']}'>{$template['tplname']}</option>";
		}
		$this->assign( 'tploptions', $tploptions );
	
		$page = $p->show ();
		$this->assign( 'map', $map );
		$this->assign('status', $status );
		$this->assign ( "page", $page );
		$this->assign( 'tradelist', $tradelist);
		$this->display("tradelist3");
	
	}
	
	function inventorylist(){
		$proskus = D('Productsetting')->getInventoryList();
		$this->assign( 'proskus', $proskus );
		$this->display();
	}
	
	
	/**
	 * @todo	订单状态检查如果是合并的怎么处理单个状态
	 * 			处理具体的发货
	 * @todo 	提交订单，查看订单如果是系统已发货.是否需要禁止。
	 * @todo	检查订单ID是否是已合并列表中存在的订单ID。
	 * @todo	待检查ID不是主ID，并且在tids 是不是需要禁止提交。 
	 */
	public function tradesend() {
		$tid = $_POST ['tid'];
		$tradeinfo  = D('Trade')->where( "tid=$tid")->find();
		$tids = $tradeinfo['systids'];
		$sendtid = $tradeinfo['systids'] ? $tradeinfo['systids'] : $tid ;
		if( empty($tradeinfo ) ) $this->error( '订单错误' );
		$company = D('Company')->where("id={$tradeinfo ['syscomid']}")->find();
		$company_code = $company['code'];
		$out_sid = $tradeinfo ['out_sid']; // 物流公司运单号
		if( empty( $out_sid) ) $this->error( '系统未提供运单号，请联系系统管理员' ) ;
		
		
		$tc = new TopClient();
		//检查订单状态
		//foreach( $tradelist as $k=>$tmporder ) {
			//$tids .= $tmporder['tid'].';';
				
			$params = array (
					'method' => 'taobao.trade.fullinfo.get',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
						
					'fields' => 'status,orders.logistics_company,orders.invoice_no',
					//'tid' => $tmporder['tid'],
					'tid' => $tid,
			);
			
			$fullinfo = $tc->getResult( $params );
			
			//$tradelist[$k]['fullinfo'] 	= 	$fullinfo['trade_fullinfo_get_response']['trade'];
			$tradeapiinfo = $fullinfo['trade_fullinfo_get_response']['trade'];
		//	}
		
		//print_r( $tradeapiinfo );
		//检查状态
		if( $tradeapiinfo[status] != 'WAIT_SELLER_SEND_GOODS' ){
			$d['status'] = $tradeapiinfo[status];
			D('Trade')->where("tid={$tid}")->save($d);
			$this->error( '订单状态为:'. $tradeapiinfo[status] );
			 
		}else {
			//可以发货
			for( $i=0;$i<3;$i++) {
				$params = array();
				if( $tids ) {
					$tids = explode(',', $tids );
					foreach ($tids as $tidTmp ) {
						for( $j=0; $j<3; $j++ ) {
							$params = array (
									'method' => 'taobao.logistics.offline.send',
									'session' => $this->_top_session,
									'timestamp' => date ( 'Y-m-d H:i:s' ),
									'format' => TAO_RETURN_FORMAT,
									'app_key' => TAO_APPKEY,
									'v' => '2.0',
									'sign_method' => 'md5',
									'tid' => $tidTmp,
									'out_sid' => $out_sid,
									'company_code' => $company_code
							);
							$result = $tc->getResult ( $params );
							if(! empty( $result ) ) break;
							Log::write( 'TRADE_SEND::::'.var_export( $result, true).'_i:'.$i.'_tid:'.$tidTmp.'--tids:'. $tradeinfo['systids'] .'_user:'.$_SESSION['seller_nick'], LOG::INFO );
						}
						
					}
					
				}else {
					$params = array (
							'method' => 'taobao.logistics.offline.send',
							'session' => $this->_top_session,
							'timestamp' => date ( 'Y-m-d H:i:s' ),
							'format' => TAO_RETURN_FORMAT,
							'app_key' => TAO_APPKEY,
							'v' => '2.0',
							'sign_method' => 'md5',
							'tid' => $tid,
							'out_sid' => $out_sid,
							'company_code' => $company_code
					);
					$result = $tc->getResult ( $params );
					if(! empty( $result ) ) break;
					Log::write( 'TRADE_SEND::::'.var_export( $result, true).'_i:'.$i.'_tid:'.$tid.'_user:'.$_SESSION['seller_nick'], LOG::INFO );
				}
				
				
				
			}
			#Log::write( 'TRADE_SEND_BEFORE::::'.var_export( $params, true), LOG::INFO );
			
			
			if ($result ['error_response']) {
				$this->error ( $result ['error_response'] ['msg'] );
			} else if ($result ['delivery_offline_send_response'] ['shipping'] ['is_success']) {
				//print_r( $result );
				//更新运单号
// 				$data['out_sid'] = $out_sid ;
// 				$data['sysstatus'] = TradeAction::TRADE_STATUS_SHIPPED ;
// 				D('Trade')->where("tid={$tid}")->save($data);
				// 记录到日志
				$vo ['tid'] = $tid;
				$vo ['loguser'] = $_SESSION ['seller_nick'];
				$vo ['logtext'] = '卖家发货';
				$vo ['logtime'] = date ( 'Y-m-d H:i:s' );
				$vo ['role'] =  $_SESSION['role'] ;
				D ( 'Tradelog' )->add ( $vo );
			
				$this->ajaxReturn ( $result, '发货成功，订单状态变更为 [卖家已发货] ', 1 );
			
			} else {
				$this->error ( '未知错误' );
			}
			
		}
		
		
		
	}
	
	
	/**
	 * 批量发货
	 */
	public function tradesendall() {
		$tidall = $_POST ['tid'];
		if( empty( $tidall ) ) $this->error( '未提交订单' );
		
		$tc = new TopClient();
		
		foreach ( $tidall as $tid ) {
			$tradeinfo  = D('Trade')->where( "tid=$tid")->find();
			$tids = $tradeinfo['systids'];
			$sendtid = $tradeinfo['systids'] ? $tradeinfo['systids'] : $tid ;
			if( empty($tradeinfo ) ) {	
				$error = "ERR:{$tid} [订单错误]<br>";
			}
			$company = D('Company')->where("id={$tradeinfo ['syscomid']}")->find();
			$company_code = $company['code'];
			$out_sid = $tradeinfo ['out_sid']; // 物流公司运单号
			if( empty( $out_sid) ) {
				$error .= "ERR:{$tid} [系统未提供运单号]<br>" ;
				continue;
			}
		
		
			
			//检查订单状态
			//foreach( $tradelist as $k=>$tmporder ) {
			//$tids .= $tmporder['tid'].';';
		
			$params = array (
					'method' => 'taobao.trade.fullinfo.get',
					'session' => $this->_top_session,
					'timestamp' => date ( 'Y-m-d H:i:s' ),
					'format' => TAO_RETURN_FORMAT,
					'app_key' => TAO_APPKEY,
					'v' => '2.0',
					'sign_method' => 'md5',
		
					'fields' => 'status,orders.logistics_company,orders.invoice_no',
					//'tid' => $tmporder['tid'],
					'tid' => $tid,
			);
				
			$fullinfo = $tc->getResult( $params );
				
			//$tradelist[$k]['fullinfo'] 	= 	$fullinfo['trade_fullinfo_get_response']['trade'];
			$tradeapiinfo = $fullinfo['trade_fullinfo_get_response']['trade'];
			//	}
		
			//print_r( $tradeapiinfo );
			//检查状态
			if( $tradeapiinfo[status] != 'WAIT_SELLER_SEND_GOODS' ){
				$d['status'] = $tradeapiinfo[status];
				D('Trade')->where("tid={$tid}")->save($d);
				$error .= "ERR:{$tid} [订单状态为 {$tradeapiinfo[status]}]<br>";
				continue;
			}else {
				//可以发货
				for( $i=0;$i<3;$i++) {
					$params = array();
					if( $tids ) {
						$tids = explode(',', $tids );
						foreach ($tids as $tidTmp ) {
							for( $j=0; $j<3; $j++ ) {
								$params = array (
										'method' => 'taobao.logistics.offline.send',
										'session' => $this->_top_session,
										'timestamp' => date ( 'Y-m-d H:i:s' ),
										'format' => TAO_RETURN_FORMAT,
										'app_key' => TAO_APPKEY,
										'v' => '2.0',
										'sign_method' => 'md5',
										'tid' => $tidTmp,
										'out_sid' => $out_sid,
										'company_code' => $company_code
								);
								$result = $tc->getResult ( $params );
								if(! empty( $result ) ) break;
								Log::write( 'TRADE_SEND::::'.var_export( $result, true).'_i:'.$i.'_tid:'.$tidTmp.'--tids:'. $tradeinfo['systids'] .'_user:'.$_SESSION['seller_nick'], LOG::INFO );
							}
							
						}
						
					}else {
						$params = array (
								'method' => 'taobao.logistics.offline.send',
								'session' => $this->_top_session,
								'timestamp' => date ( 'Y-m-d H:i:s' ),
								'format' => TAO_RETURN_FORMAT,
								'app_key' => TAO_APPKEY,
								'v' => '2.0',
								'sign_method' => 'md5',
								'tid' => $tid,
								'out_sid' => $out_sid,
								'company_code' => $company_code
						);
						$result = $tc->getResult ( $params );
						if(! empty( $result ) ) break;
						Log::write( 'TRADE_SEND::::'.var_export( $result, true).'_i:'.$i.'_tid:'.$tid.'_user:'.$_SESSION['seller_nick'], LOG::INFO );
					}
					
					
					
				}
				#Log::write( 'TRADE_SEND_BEFORE::::'.var_export( $params, true), LOG::INFO );
					
					
				if ($result ['error_response']) {
					$error .= "ERR:{$tid}:{$result ['error_response'] ['msg']} <br>" ;
				} else if ($result ['delivery_offline_send_response'] ['shipping'] ['is_success']) {
				//print_r( $result );
					//更新运单号
					// 				$data['out_sid'] = $out_sid ;
					// 				$data['sysstatus'] = TradeAction::TRADE_STATUS_SHIPPED ;
					// 				D('Trade')->where("tid={$tid}")->save($data);
					// 记录到日志
					$vo ['tid'] = $tid;
					$vo ['loguser'] = $_SESSION ['seller_nick'];
					$vo ['logtext'] = '卖家发货';
					$vo ['logtime'] = date ( 'Y-m-d H:i:s' );
					$vo ['role'] =  $_SESSION['role'] ;
					D ( 'Tradelog' )->add ( $vo );
						
					$success .= "OK:{$tid} [卖家已发货]<br>";
						
				} else {
					#$this->error ( '未知错误' );
				}
					
			}
	
		}
		$this->ajaxReturn( '', $error . $success , 1 );
			
	
	}
		
	
	
	
	function filterTrades( $orders ){
		$t = D('Trade');
		 
		foreach( $orders['trades_sold_get_response']['trades']['trade'] as $k=>$trade ) {
			if( $t->filterTrade( number_format( $trade['tid'], 0, '', '' ) )  ) {
				unset( $orders['trades_sold_get_response']['trades']['trade'][$k] );
			}
		}
		return $orders ;		
	 
		
	}
	/**
	 * 根据合并的订单ID过滤
	 * @param $orders	订单
	 * @param $orderM	合并的订单
	 */
	function filterMergeTrade ( $orders ,$orderM ) {
		foreach( $orderM as $orderTmp ){
			$tids .= $orderTmp['systids'].',';
			
		}
		 
		if($tids ) {
			$tids = trim( $tids, ',');
			$tids = explode( ',', $tids );
		}
		#print_r( $tids ) ;
		#echo 'before:'. count( $orders['trades_sold_get_response']['trades']['trade'] );
		foreach( $orders['trades_sold_get_response']['trades']['trade'] as $k=>$trade ) {
			if(  in_array( number_format( $trade['tid'], 0, '', '' ) , $tids )   ) {
				unset( $orders['trades_sold_get_response']['trades']['trade'][$k] );
			}
		}
		#echo 'after:'. count( $orders['trades_sold_get_response']['trades']['trade'] );
		return $orders ;
	}
	
}

